﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Conversive.PHPSerializationLibrary;
using FaceMqttClient;
using Flurl.Http;
using Furion;
using Furion.LinqBuilder;
using Furion.Logging;
using Furion.Schedule;
using Furion.TimeCrontab;
using NetTaste;
using Newtonsoft.Json;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using StackExchange.Redis;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.WxaBusinessGetUserEncryptKeyResponse.Types;

namespace MqttClient.Jobs
{
    [PeriodSeconds(20)]
    [JobDetail(jobId: "微信通知", description: "微信通知", GroupName = "系统", Concurrent = false)]
    public class WxsendJob1 : IJob
    {
        public string server = "https://weixin.tslexunbao.com";

        //        ConnectionMultiplexer redis;
        string pkey = "easywechat.kernel.access_token*";
        static string key = "";
        PhpSerializer ps = new PhpSerializer();
        static bool send = false;

        /// <summary>
        ///  微信token
        /// </summary>
        private string token;
        private readonly WechatApiClientOptions options;

        public WxsendJob1()
        {
            options = new WechatApiClientOptions()
            {
                AppId = "wx42a8bcc9d53bcf3b",
                AppSecret = "673321d209f6c3e3b4d8d9eb6fce56a6",
            };
        }

        /// <summary>
        /// 微信通知
        /// </summary>
        /// <param name="context"></param>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
        {
            //  Console.WriteLine("WxsendJob1");
            {
                // var services = scope.ServiceProvider;
                try
                {
                    var server = RedisHelper.GetServer("127.0.0.1", 6379);
                    while (key.IsNullOrEmpty())
                    {
                        await "https://weixin.tslexunbao.com/wxapi/app/acctoken".GetAsync();

                        foreach (var akey in RedisHelper.GetLikeKeys(pkey))
                        {
                            //  Console.WriteLine(key);
                            key = akey;
                            Console.WriteLine(akey);
                        }
                        Thread.Sleep(1000);
                    }
                    var dbredis = RedisHelper.GetDatabase();
                    var str = (dbredis.StringGet(key));
                    if (!String.IsNullOrEmpty(str))
                    {
                        var t = (Dictionary<object, object>)ps.Deserialize(str);
                        if (t.ContainsKey("access_token"))
                        {
                            token = t["access_token"].ToString();
                        }

                        if (!send)
                        {
                            send = true;
                            await OnlineNoticeMe(token);
                        }

                        Console.ForegroundColor = ConsoleColor.White;

                        var wxtz = App.GetService<WeixinTongzhi>(); // services.GetService<WeixinTongzhi>();
                        using (var unsend = wxtz.getUnsend())
                        {
                            // 获取小时数
                            var h = DateTime.Now.Hour;
                            foreach (DataRow kaoqin in unsend.Rows)
                            {
                                try
                                {
                                    StringLoggingPart
                                        .Default()
                                        .SetMessage(
                                            $"{kaoqin["address"]}  {kaoqin["clname"]} {kaoqin["username"]} 开始发送"
                                        )
                                        .LogWarning();

                                    using (var untz = wxtz.getTongzhi(kaoqin["uid"].ToString()))
                                    {
                                        foreach (DataRow guanzhu in untz.Rows)
                                        {
                                            var f = wxtz.cansend(
                                                guanzhu["slname"].ToString(),
                                                kaoqin
                                            ).Result;
                                            if (f == true)
                                            {
                                                BuildKaoqinMsg(token, kaoqin, guanzhu);
                                            }
                                            else
                                            {
                                                StringLoggingPart
                                                    .Default()
                                                    .SetMessage(
                                                        $"{kaoqin["address"]}  {kaoqin["clname"]} {guanzhu["username"]} 不发送"
                                                    )
                                                    .LogWarning();
                                            }
                                        }
                                    }

                                    if (!kaoqin["sn"].ToString().Equals("00000"))
                                    {
                                        if (
                                            kaoqin["zschool"].ToString().Equals("是")
                                            || kaoqin["dx"].ToString().Equals("是")
                                        )
                                        {
                                            if (wxtz.LeaveSchool(kaoqin["slname"].ToString()))
                                            {
                                                //仅仅是住宿生发信息
                                                if (
                                                    (h >= 11 && h <= 13)
                                                    || // 中午
                                                    (
                                                        h >= 16
                                                        && !wxtz.Isholiday(
                                                            DateTime.Now.AddDays(1)
                                                        ).Result
                                                        && kaoqin["zschool"].ToString().Equals("是")
                                                    ) // 下午 明天不是假期
                                                )
                                                {
                                                    // 中午

                                                    using (
                                                        var tctz = wxtz.getTongzhiTeacher(
                                                            kaoqin["classname"].ToString()
                                                        )
                                                    )
                                                    {
                                                        if (tctz != null)
                                                        {
                                                            foreach (DataRow laoshi in tctz.Rows)
                                                            {
                                                                LevelMsg(token, kaoqin, laoshi);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    StringLoggingPart
                                        .Default()
                                        .SetMessage($"{e.Message} ")
                                        .LogError();

                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine(e.Message);
                                    Console.ForegroundColor = ConsoleColor.White;
                                }
                                if (send)
                                    wxtz.Sended(Convert.ToInt32(kaoqin["Lid"]));
                                else
                                    break;
                            }
                        }

                        using (var unsend = wxtz.getUnsendTeacher())
                        {
                            foreach (DataRow kaoqin in unsend.Rows)
                            {
                                try
                                {
                                    using (var untz = wxtz.getBindTeacher(kaoqin["uid"].ToString()))
                                    {
                                        foreach (DataRow guanzhu in untz.Rows)
                                        {
                                            Console.WriteLine(guanzhu["oauth_id"]);
                                            BuildKaoqinMsgTeacher(token, kaoqin, guanzhu);
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    StringLoggingPart
                                        .Default()
                                        .SetMessage($"{e.Message} ")
                                        .LogError();

                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine(e.Message);
                                    Console.ForegroundColor = ConsoleColor.White;
                                }
                                if (send)
                                    wxtz.Sended(Convert.ToInt32(kaoqin["Lid"]));
                                else
                                    break;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    StringLoggingPart.Default().SetMessage($"{e.Message} ").LogError();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("微信通知 失败 " + e.Message + e.StackTrace);
                    if (e.InnerException != null)
                    {
                        Console.WriteLine(
                            "微信通知 失败 "
                                + e.InnerException.Message
                                + e.InnerException.StackTrace
                        );
                    }
                    Console.ForegroundColor = ConsoleColor.White;
                }
            }
        }

        /// <summary>
        /// 发送在线消息
        /// </summary>
        /// <param name="token"></param>
        private async Task OnlineNoticeMe(string token)
        {
            await "https://weixin.tslexunbao.com/wxapi/app/acctoken".GetAsync();

            CgibinMessageTemplateSendRequest tplr = new CgibinMessageTemplateSendRequest();
            tplr.TemplateId = "ENpttNmhOaEhxCiUW0TN4a2_Gc3G6_-XKgrlZCrcHrk";
            tplr.Data = new Dictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>();
            // 头
            tplr.Data.Add(
                "first",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value = "服务器PAYMQTTclient上线了",
                }
            );
            // 姓名
            tplr.Data.Add(
                "keyword1",
                new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "MQTT" }
            );
            // 时间
            tplr.Data.Add(
                "keyword2",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm"),
                }
            );
            // 地点
            tplr.Data.Add(
                "keyword3",
                new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "服务器" }
            );
            // 备注
            tplr.Data.Add(
                "remark",
                new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "请注意查收" }
            );
            tplr.ToUserOpenId = "oyXHL0qFna08ZW-mnlDUiYEjOMW8";
            tplr.AccessToken = token;
            //tplr.Url = "";

            var client = new WechatApiClient(options);
            client.ExecuteCgibinMessageTemplateSendAsync(tplr);
        }

        /// <summary>
        /// 发送考勤通知
        /// </summary>
        /// <param name="token"></param>
        /// <param name="stu"></param>
        /// <param name="jiazhang"></param>
        private void BuildKaoqinMsgTeacher(string token, DataRow stu, DataRow jiazhang)
        {
            CgibinMessageTemplateSendRequest tplr = new CgibinMessageTemplateSendRequest();
            tplr.TemplateId = TplIds.学生刷脸;
            tplr.Data = new Dictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>();

            var date = Convert.ToDateTime(stu["time"]).ToString("yyyy-MM-dd HH:mm");
            // 姓名
            tplr.Data.Add(
                "name",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value = stu["username"].ToString(),
                    Color = "#173177",
                }
            );
            // 时间
            tplr.Data.Add(
                "time",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value = date,
                    Color = "#173177",
                }
            );
            // 地点
            tplr.Data.Add(
                "location",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value = stu["address"].ToString(),
                    Color = "#173177",
                }
            );

#if DEBUG
            tplr.ToUserOpenId = "oyXHL0qFna08ZW-mnlDUiYEjOMW8";
#else
            tplr.ToUserOpenId = jiazhang["oauth_id"].ToString();
#endif
            tplr.AccessToken = token;
            //tplr.Url = "http://weixin.tslexunbao.com/user/kaoqin_log/index/" + stu["uid"];



            var client = new WechatApiClient(options);
            client
                .ExecuteCgibinMessageTemplateSendAsync(tplr)
                .ContinueWith(
                    (
                        res =>
                        {
                            var msg = res.Result.ErrorMessage.ToString();

                            if (msg.Contains("access_token is invalid"))
                            {
                                send = false;
                            }
                            // Console.WriteLine($"{DateTime.Now.ToString("yyyy/MM/dd HH:mm")} {stu["sbid"]} {stu["username"]} {tplr.ToUserOpenId}->{stu["Lid"]}  {res.Result.ErrorMessage}");

                            StringLoggingPart
                                .Default()
                                .SetMessage(
                                    $"{stu["address"]}  时间:{date}  {stu["sbid"]} {stu["username"]}  {JsonConvert.SerializeObject(tplr)}{tplr.ToUserOpenId}->{stu["Lid"]}  {msg}"
                                )
                                .LogWarning();
                        }
                    )
                );
        }

        /// <summary>
        /// 发送考勤通知
        /// </summary>
        /// <param name="token"></param>
        /// <param name="stu"></param>
        /// <param name="jiazhang"></param>
        private void BuildKaoqinMsg(string token, DataRow stu, DataRow jiazhang)
        {
            CgibinMessageTemplateSendRequest tplr = new CgibinMessageTemplateSendRequest();
            tplr.TemplateId = TplIds.学生刷脸;
            tplr.Data = new Dictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>();
            string msg = "有一条考勤消息";
            if (stu["sn"].ToString().Equals("00000"))
            {
                msg = "已到课堂";
            }
            int stat = Convert.ToInt32(stu["state"]);
            switch (stat)
            {
                case 1:
                    // 未到
                    msg = "点名时未到课堂。";
                    break;
                case 2:
                    // 请假
                    msg = "请假未到课堂。";
                    break;
                case 3:
                    // 迟到
                    msg = "课堂点名迟到。";
                    break;
                default:
                    break;
            }

            int io = Convert.ToInt32(stu["io"]);
            switch (io)
            {
                case 1:
                    msg = "已经进校";
                    break;

                case 2:
                    msg = "已经离校";
                    break;
            }

            string adname = "";
            int adid = Convert.ToInt32(stu["adid"]);
            if (adid > 0)
            {
                var kls = App.GetService<Kaoqin_logService>();
                var ad = kls.getAdbyid(adid);
                if (ad != null)
                {
                    adname = ad.title + "提醒您";
                }
            }

            var date = Convert.ToDateTime(stu["time"]).ToString("yyyy-MM-dd HH:mm");
            // 头
            tplr.Data.Add(
                "first",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value =
                        $"亲爱的{jiazhang["username"]}家长,{adname} {jiazhang["username"]}同学{msg}",
                    Color = "#173177",
                }
            );
            // 姓名
            tplr.Data.Add(
                "name",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value = jiazhang["username"].ToString(),
                    Color = "#173177",
                }
            );
            // 时间
            tplr.Data.Add(
                "time",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value = date,
                    Color = "#173177",
                }
            );
            // 地点
            tplr.Data.Add(
                "location",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value = stu["address"].ToString(),
                    Color = "#173177",
                }
            );
            // 备注
            tplr.Data.Add(
                "remark",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value = "点击这里查看详情\n↓↓↓↓↓↓↓",
                    Color = "#ff0000",
                }
            );
#if DEBUG
            tplr.ToUserOpenId = "oyXHL0qFna08ZW-mnlDUiYEjOMW8";
#else
            tplr.ToUserOpenId = jiazhang["oauth_id"].ToString();
#endif
            tplr.AccessToken = token;
            tplr.Url = "http://weixin.tslexunbao.com/user/kaoqin_log/index/" + stu["uid"];

            var client = new WechatApiClient(options);
            client
                .ExecuteCgibinMessageTemplateSendAsync(tplr)
                .ContinueWith(
                    (
                        res =>
                        {
                            Console.WriteLine(
                                $"{DateTime.Now.ToString("yyyy/MM/dd HH:mm")} {stu["clname"]} {jiazhang["username"]} {tplr.ToUserOpenId}->{stu["Lid"]}  {res.Result.ErrorMessage}"
                            );

                            StringLoggingPart
                                .Default()
                                .SetMessage(
                                    $"{stu["address"]}  {stu["clname"]} {jiazhang["username"]}  {JsonConvert.SerializeObject(tplr)}{tplr.ToUserOpenId}->{stu["Lid"]}  {res.Result.ErrorMessage}"
                                )
                                .LogWarning();
                        }
                    )
                );
        }

        /// <summary>
        /// 发送离校消息
        /// </summary>
        /// <param name="token"></param>
        private void LevelMsg(string token, DataRow stu, DataRow laos)
        {
            CgibinMessageTemplateSendRequest tplr = new CgibinMessageTemplateSendRequest();
            tplr.TemplateId = TplIds.离校教师;
            tplr.Data = new Dictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>();
            // 头
            tplr.Data.Add(
                "first",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value =
                        $"{laos["username"]}您好: {stu["username"]}刚刚在{stu["address"]}附近出现。",
                }
            );
            // 姓名
            tplr.Data.Add(
                "keyword1",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value = stu["username"].ToString(),
                    Color = "#173177",
                }
            );
            // 时间
            tplr.Data.Add(
                "keyword2",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm"),
                }
            );
            // 地点
            tplr.Data.Add(
                "keyword3",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value = stu["address"].ToString(),
                }
            );
            // 备注
            tplr.Data.Add(
                "remark",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                {
                    Value = "如果孩子非正常离校,请及时处理。",
                    Color = "#ff0000",
                }
            );
#if DEBUG
            tplr.ToUserOpenId = "oyXHL0qFna08ZW-mnlDUiYEjOMW8";
#else
            tplr.ToUserOpenId = laos["oauth_id"].ToString();
#endif

            tplr.AccessToken = token;
            //tplr.Url = "";


            var client = new WechatApiClient(options);
            client.ExecuteCgibinMessageTemplateSendAsync(tplr);
        }
    }
}
